package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService  workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 1.准备日期列表数据 dateList
        List<LocalDate> dateList = getDateList(begin, end);

        // 2.准备营业额列表数据 turnoverList
        List<Double> turnoverList = new ArrayList<>();
        // 营业额 = 订单状态已完成的
        // 查询orders表，根据日期范围和订单状态查询营业额
        dateList.forEach(date -> {
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); // 00:00:00
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX)); // 23:59:59
            Double turnover = ordersMapper.sumByMap(map);
            // 营业额为null，默认0.0
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        });

        // 3.封装VO对象
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 1.获取日期列表数据
        List<LocalDate> dateList = getDateList(begin, end);
        // 2.构造newUserList数据，新增用户列表
        List<Integer> newUserList = new ArrayList<>();
        // 3.构造totalUserList数据，总用户列表
        List<Integer> totalUserList = new ArrayList<>();

        // 循环遍历日期列表，统计每日的新增用户数和总用户数
        dateList.forEach(date -> {
            Map map = new HashMap();

            // 查询新增用户数
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); // 00:00:00
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX)); // 23:59:59
            Integer newUser = userMapper.countByMap(map);
            newUserList.add(newUser);

            // 查询总用户数
            map.put("beginTime", null);
            Integer totalUser = userMapper.countByMap(map);
            totalUserList.add(totalUser);
        });

        // 4.封装VO对象
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    /*
    * 订单统计
    * @param begin
    * @param end
    * @return
    */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        // 1.获取日期列表数据
        List<LocalDate> dateList = getDateList(begin, end);

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        // 循环遍历日期列表进行订单统计
        for (LocalDate date : dateList) {
            // 2.获取每日总订单列表数 orderCountList
            // 统计每日orders表数量，条件： 下单时间在日期范围内
            Map map = new HashMap();
            map.put("beginTime", LocalDateTime.of(date, LocalTime.MIN)); // 00:00:00
            map.put("endTime", LocalDateTime.of(date, LocalTime.MAX)); // 23:59:59
            Integer totalOrder = ordersMapper.countByMap(map);
            orderCountList.add(totalOrder);

            // 3.获取每日有效订单列表数 validOrderCountList
            // 统计每日有效orders表数量，条件：状态为已完成，下单时间在日期范围内
            map.put("status", Orders.COMPLETED);
            Integer validOrder = ordersMapper.countByMap(map);
            validOrderCountList.add(validOrder);

            // 4.获取区间订单总数
            totalOrderCount += totalOrder;
            // 5.获取区间有效订单数
            validOrderCount += validOrder;
        }

        // 6.获取订单完成率
        Double orderCompletionRate = 0.0;
        if(totalOrderCount != 0){
            orderCompletionRate = (validOrderCount + 0.0) / totalOrderCount;
        }
        // 7.返回vo
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量排名前10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        // 1.构造nameList 商品名称列表
        List<String> nameList = new ArrayList<>();
        // 2.构造numberList 销量列表
        List<Integer> numberList = new ArrayList<>();

        // 查询orders表和order_detail表 条件：订单状态-已完成，下单时间
        Map map = new HashMap();
        map.put("status", Orders.COMPLETED);
        map.put("beginTime", LocalDateTime.of(begin, LocalTime.MIN)); // 00:00:00
        map.put("endTime", LocalDateTime.of(end, LocalTime.MAX)); // 23:59:59
        List<GoodsSalesDTO> list = ordersMapper.sumTop10(map);

        for(GoodsSalesDTO dto : list){
            nameList.add(dto.getName());
            numberList.add(dto.getNumber());
        }

        // 3.封装VO对象
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        // 1.查询数据库，获取营业数据---
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        // 2.通过poi将数据写入到excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            // 基于模板文件创建excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            // 获取表格文件的Sheet页
            XSSFSheet sheet = excel.getSheet("sheet1");

            // 填充数据
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);
            XSSFRow row4 = sheet.getRow(3);
            row4.getCell(2).setCellValue(businessDataVO.getTurnover());
            row4.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row4.getCell(6).setCellValue(businessDataVO.getNewUsers());

            XSSFRow row5 = sheet.getRow(4);
            row5.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row5.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            // 填充明细数据
            for (int i = 0; i < 30; i++){
                LocalDate date = dateBegin.plusDays(i);
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                // 获得某一行
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            // 3.通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取日期列表数据
     * @param begin
     * @param end
     * @return dateList
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        while (begin.isBefore(end)) {
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        log.info("dateList={}", dateList);
        return dateList;
    }
}
